package net.chenpu.gae.proxy.remote;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.chenpu.gae.proxy.Constants;
import net.chenpu.gae.proxy.IO;

@SuppressWarnings("serial")
public class GaeProxyServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(GaeProxyServlet.class
			.getName());

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String accessPath = request.getHeader(Constants.URL_HEADER);
		log.info("access: " + accessPath);
		URL accessUrl = new URL(accessPath);
		HttpURLConnection connection = (HttpURLConnection) accessUrl
				.openConnection();

		// Set http client request method
		String method = request.getMethod();
		connection.setRequestMethod(method);

		// Set http client reqeust headers
		Enumeration<String> headers = request.getHeaderNames();
		while (headers.hasMoreElements()) {
			String header = headers.nextElement();
			if (header.equals(Constants.URL_HEADER))
				continue;
			if (header.equals("Host")) {
				continue;
			}

			if (header.equalsIgnoreCase("Cookie"))
				log.info("request cookie: " + request.getHeader(header));

			connection.setRequestProperty(header, request.getHeader(header));
		}

		// Set http client request content
		if (method.equalsIgnoreCase("POST")) {
			connection.setDoOutput(true);
			IO.copy(request.getInputStream(), connection.getOutputStream());
			connection.getOutputStream().close();
		}
		
		int status = connection.getResponseCode();
		response.setStatus(status);

		// Set response headers
		Iterator<String> headerIter = connection.getHeaderFields().keySet()
				.iterator();

		while (headerIter.hasNext()) {
			String header = headerIter.next();
			if (header == null)
				continue;
			String value = connection.getHeaderField(header);
			log.info("find header," + header + ": " + value);
			response.setHeader(header, value);
		}
		response.setContentLength(connection.getContentLength());
		response.setCharacterEncoding(connection.getContentEncoding());
		response.setContentType(connection.getContentType());
		// Set response content
		IO.copy(connection.getInputStream(), response.getOutputStream());
		response.getOutputStream().close();

	}
}
